import numpy as np
from PIL import Image
import os
import random
from siamese import Siamese

def get_test_imgs(path):
    file = os.listdir(path)
    file.sort(key=lambda x: int(x))
    test_imgs = []
    for character in file:
        character_path = os.path.join(path, character)
        for image in os.listdir(character_path):
            test_imgs.append(os.path.join(character_path, image))
    return test_imgs

def randint_digit(low, high, cutoff):
    """用来生成一个在区间[low, high)排除cutoff后的随机整数

    Parameters
    ----------
    low: int
        下限，能够取到
    high: int
        上限，不能够取到
    cutoff: int/list
        一个需要剔除的数或者数组，要求在(low, high)区间之间
    """
    digit_list = list(range(low, high))
    if type(cutoff) is int:  # 只需要剔除一个值
        if cutoff in digit_list:  # 如果需要剔除的值不存在，则不执行剔除操作
            digit_list.remove(cutoff)
    else:
        for i in cutoff:  # 需要剔除多个值的情况
            if i not in digit_list:  # 如果需要剔除的值不存在，则不执行剔除操作
                continue
            digit_list.remove(i)

    np.random.shuffle(digit_list)

    return digit_list.pop()  # 生成的序列打乱并且返回当前的随机值

if __name__ == "__main__":
    #一组正对照，两组反对照
    model = Siamese()

    imgs = get_test_imgs("test_imgs")
    result = []
    # result.append(1)
    for i in range(int(len(imgs)/2)):
        image_1 = imgs[i*2]
        image_2 = imgs[i * 2+1]

        # r = random.randint(0, 1)
        # if i == 0:
        #     image_3 = image_1
        # else:
        #     image_3 = image_2

        image_3 = image_1

        r = random.randint(0, len(imgs))
        if r == i*2:
            r = random.randint(0, len(imgs))
        image_4 = imgs[r]

        image_5 = image_2
        if r-2 < len(imgs):
            image_6 = imgs[r+2]
        else:
            image_6 = imgs[r - 2]

        image_1 = Image.open(image_1)
        image_2 = Image.open(image_2)
        image_3 = Image.open(image_3)
        image_4 = Image.open(image_4)
        image_5 = Image.open(image_5)
        image_6 = Image.open(image_6)

        probability = model.detect_image(image_1,image_2).item()
        result.append(probability)
        print(i * 2, "-", probability)

        probability = model.detect_image(image_3, image_4).item()
        result.append(probability)
        print(i * 2 + 1, "-", probability)

        probability = model.detect_image(image_5, image_6).item()
        result.append(probability)
        print(i * 2 + 1, "-", probability)

    T = 0
    F = 0

    for i in range(result):
        if i % 3 ==0:
            if result[i] >= 0.8:
                T = T+1
            else:
                F = F + 1
        else:
            if result[i] <= 0.2:
                T = T + 1
            else:
                F = F + 1

    P = T / (T + F)

    print(P)
